//效验价格
function checkPrice (rules, value, callback){
    if (!value) {
        callback(new Error('请填写菜品价格'))
    } else {
        const reg = /^\d+(\.\d{0,2})?$/
        if (reg.test(value)) {
            if(value < 10000){
                callback()
            }else{
                callback(new Error('菜品价格小于10000'))
            }
        } else {
            callback(new Error('菜品价格格式只能为数字,且最多保留两位小数'))
        }
    }
}

Vue.config.productionTip=false  //以阻止 vue 在启动时生成生产提示。 <!-- 全局配置 -->
new Vue({
    el: '#food-app',
    data: {
        //当前登录的用户信息
        user: {
            name: 'admin',

        },
        //查看菜品信息
        input: '',     //搜索内容
        total: 0,            //总条目数
        currentPage: 1,             //当前显示页数
        pageSize: 10,        //每页所支持的最大条数
        pages : 1,           //总页数
        tableData: [        //表单内容

        ],
        checkList: [],     //复选框被选中的id列表
        //添加菜品
        dialogAddFormVisible: false,
        elAdd:{
            name: '',
            categoryId: null,
            price: null,
            flavors: [],
            image: '',
            code: '',
            sort: null,
            description: ''
        },
        typeList: [     //菜品类型

        ],
        tasteList: ['酸辣','麻辣','微辣','三鲜','不要香菜','不要葱'],     //口味列表
        //修改
        dialogUpdateFormVisible:false,
        elUpdate:{
            id: null,
            name:'',
            categoryId:'',
            price:'',
            flavors:[],
            image:'',
            code: '',
            sort: null,
            description:''
        },
        //效验
        rules:{
            name: [{required: true, message: '请填写菜品名称', trigger: blur}],
            categoryId: [{required: true, message: '请选择菜品分类', trigger: blur}],
            price: [{required: true, validator: checkPrice, trigger: blur}],
            sort: [{required: true, message: '请设置菜品序号', trigger: blur}],
            code: [{required: true, message: '请填写菜品商品码', trigger: blur}]
        },
    },
    created(){
        this.init();
    },
    methods: {
        //加载列表数据
        init() {
            axios({
                methods: "get",
                url: "/dish/page",
                params:{
                    name: this.input,
                    currentPage:this.currentPage,
                    pageSize: this.pageSize,
                }
            }).then((res)=>{
                if(res.data.code==1){
                    this.tableData=res.data.data.records;
                    this.total=parseInt(res.data.data.total);      //总条目数
                    this.pageSize=parseInt(res.data.data.size);    //每页所支持的最大条数
                    this.pages=parseInt(res.data.data.pages);      //总页数
                }else{
                    this.$message.error(res.data.msg);
                }
            });
        },
        //批量操作复选框
        handleSelectionChange(row){
            let checkArr = [];     //复选框被选中的id列表
            row.forEach((val) => {
                checkArr.push(val.id)
            });
            this.checkList = checkArr;        //checkList列表为被选中的ID列表
            console.log(this.checkList);
        },
        //批量删除
        deleteListHandle(){
            this.$confirm("确定删除此菜品信息，是否继续？","提示",{
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type: "warning"
            }).then(()=> {   //选择确定的情况
                axios({
                    method: "POST",
                    url: "/dish/deleteByIds",
                    data: this.checkList
                }).then((res)=>{
                    if(res.data.code==0){
                        this.$message.error(res.data.msg);
                    }else{
                        this.$message.success({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                }).finally(()=>{
                    this.init();
                });
            }).catch(()=>{   //选择取消的情况
                this.$message({
                    type:"into",
                    message:"已取消"
                });
            });
        },
        //批量启售或批量停售
        statusListHandle(val){
            this.$confirm("确定修改此菜品信息，是否继续？","提示",{
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type: "warning"
            }).then(()=> {   //选择确定的情况
                axios({
                    method: "POST",
                    url: "/dish/statusList/"+val,
                    data: this.checkList
                }).then((res)=>{
                    if(res.data.code==0){
                        this.$message.error(res.data.msg);
                    }else{
                        this.$message.success({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                }).finally(()=>{
                    this.init();
                });
            }).catch(()=>{   //选择取消的情况
                this.$message({
                    type:"into",
                    message:"已取消"
                });
            });
        },
        //获取菜品分类列表
        gainCategoryList(){
            axios({
                method: "get",
                url: "/category/gainCategoryList",
                params: {
                    type: 1
                }
            }).then((res)=>{
                if(res.data.code==0){
                    this.$message.error(res.data.msg);
                }else{
                    this.typeList=res.data.data;
                }
            });
        },
        //新建菜品
        showAdd(){
            this.gainCategoryList();    //获取菜品分类列表
            this.dialogAddFormVisible=true;
        },
        //提交添加
        handleAdd(){
            this.$refs.elAdd.validate((valid) => {
                if (valid) {
                    this.$confirm("确定添加此菜品，是否继续？","提示",{
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                        type: "warning"
                    }).then(()=> {   //选择确定的情况
                        axios({
                            method: "POST",
                            url: "/dish/save",
                            data:this.elAdd
                        }).then((res)=>{
                            if(res.data.code==0){
                                this.$message.error(res.data.msg);
                            }else{
                                this.$message.success({
                                    message: res.data.msg,
                                    type: 'success'
                                });
                                this.$refs.elAdd.resetFields();      //清空表单
                            }
                        }).finally(()=>{
                            this.init();
                        });
                    }).catch(()=>{   //选择取消的情况
                        this.$message({
                            type:"into",
                            message:"已取消"
                        });
                    }).finally(()=>{
                        this.dialogAddFormVisible=false;
                    });
                } else {
                    this.$message.error('此提交不符合规则');
                    return false;
                }
            });
        },

        //添加菜品的上传图片
        elAddUpload(context) {
            let formData = new FormData();
            formData.append("file",context.file);
            console.log(context.file);
            axios.post('/common/upload', formData).then(res=> {
                if (res.data.code==0) {
                    this.$message.error(res.data.msg);
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: "success"
                    });
                    this.elAdd.image = '/common/download?name='+res.data.data;
                }
            });
        },
        //上传之前的效验
        beforeUpload(file) {
            if(file){
                const suffix = file.name.split('.')[1]      //截取图片名称的后缀名
                const size = file.size / 1024 / 1024 < 20
                if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                    this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                    this.$refs.upload.clearFiles()
                    return false
                }
                if(!size){
                    this.$message.error('上传文件大小不能超过 20MB!')
                    return false
                }
                return file
            }
        },


        //显示修改菜品弹窗
        showUpdate(id){
            this.gainCategoryList();
            axios({
                method: "get",
                url: "/dish/gainByID/"+id,
            }).then((res)=>{
                if(res.data.code==0){
                    this.$message.error(res.data.msg);
                }else{
                    this.elUpdate.id=res.data.data.id;
                    this.elUpdate.name=res.data.data.name;
                    this.elUpdate.categoryId=res.data.data.categoryId;
                    this.elUpdate.price=res.data.data.price;
                    this.elUpdate.flavors=res.data.data.flavors;
                    this.elUpdate.image=res.data.data.image;
                    this.elUpdate.code=res.data.data.code;
                    this.elUpdate.sort=res.data.data.sort;
                    this.elUpdate.description=res.data.data.description;
                    this.dialogUpdateFormVisible=true;
                }
            });
        },
        //修改菜品信息
        handleUpdate(){
            this.$refs.elUpdate.validate((valid) => {
                if (valid) {
                    this.$confirm("确定修改此菜品，是否继续？","提示",{
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                        type: "warning"
                    }).then(()=> {   //选择确定的情况
                        axios({
                            method: "POST",
                            url: "/dish/update",
                            data:this.elUpdate
                        }).then((res)=>{
                            if(res.data.code==0){
                                this.$message.error(res.data.msg);
                            }else{
                                this.$message.success({
                                    message: res.data.msg,
                                    type: 'success'
                                });
                                this.$refs.elUpdate.resetFields();      //清空表单
                            }
                        }).finally(()=>{
                            this.init();
                        });
                    }).catch(()=>{   //选择取消的情况
                        this.$message({
                            type:"into",
                            message:"已取消"
                        });
                    }).finally(()=>{
                        this.dialogUpdateFormVisible=false;
                    });
                } else {
                    this.$message.error('此提交不符合规则');
                    return false;
                }
            });
        },
        //修改菜品的上传图片
        elUpdateUpload(context) {
            let formData = new FormData();
            formData.append("file",context.file);
            console.log(context.file);
            axios.post('/common/upload', formData).then(res=> {
                if (res.data.code==0) {
                    this.$message.error(res.data.msg);
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: "success"
                    });
                    this.elUpdate.image = '/common/download?name='+res.data.data;
                }
            })
        },
        //启售或停售
        statusHandle(row){
            this.$confirm("确定修改菜品状态，是否继续？","提示",{
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type: "warning"
            }).then(()=> {   //选择确定的情况
                axios({
                    method: "POST",
                    url: "/dish/setStatus",
                    data:row
                }).then((res)=>{
                    if(res.data.code==0){
                        this.$message.error(res.data.msg);
                    }else{
                        this.$message.success({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                }).finally(()=>{
                    this.init();
                });
            }).catch(()=>{   //选择取消的情况
                this.$message({
                    type:"into",
                    message:"已取消"
                });
            });
        },
        //删除菜品信息
        deleteHandle(id){
            this.$confirm("确定删除此菜品信息，是否继续？","提示",{
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type: "warning"
            }).then(()=> {   //选择确定的情况
                axios({
                    method: "Delete",
                    url: "/dish/deleteById/"+id,
                }).then((res)=>{
                    if(res.data.code==0){
                        this.$message.error(res.data.msg);
                    }else{
                        this.$message.success({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                }).finally(()=>{
                    this.init();
                });
            }).catch(()=>{   //选择取消的情况
                this.$message({
                    type:"into",
                    message:"已取消"
                });
            });
        },
        //每页显示的条目数改变时会触发
        handleSizeChange(val){
            this.pageSize = val;
            this.init()
        },
        //当前页改变时会触发
        handleCurrentChange(val){
            this.currentPage = val;
            this.init()
        }
    }
})